package gui;

import java.awt.Dialog;
import java.awt.FileDialog;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.JFileChooser;
import javax.swing.JFrame;

class Serializzatore<T> extends JFrame {
	private static final long serialVersionUID = 1L;

	// Metodo carica
	@SuppressWarnings("unchecked")
	public T carica() {
		try {

			JFileChooser filec = new JFileChooser();
			filec.setDialogTitle("Choose a file");
			// filec.showSaveDialog(this);
			filec.setVisible(true);
			filec.setCurrentDirectory(new File("./"));
			if (filec.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
				System.out.println("getCurrentDirectory(): "
						+ filec.getCurrentDirectory());
				System.out.println("getSelectedFile() : "
						+ filec.getSelectedFile());
				String filename = filec.getCurrentDirectory() + "\\"
						+ filec.getSelectedFile().getName();

				if (filename != null) {
					FileInputStream fis = new FileInputStream(filename);
					ObjectInputStream ois = new ObjectInputStream(fis);
					T object = (T) ois.readObject();
					fis.close();
					return object;
				}
			}
		} catch (IOException a) {
			System.out.println("Errore lettura dell'oggetto");
		} catch (ClassNotFoundException e) {
			System.out.println("Classe non riconosciuta!!!");
		}
		return null;
	}

	// Metodo salva
	public void salva(JFrame f, T object) {
		try {
			System.out.println("SALVA");
			JFileChooser filec = new JFileChooser();
			filec.setDialogTitle("Choose a file");
			// filec.showSaveDialog(this);
			filec.setVisible(true);
			filec.setCurrentDirectory(new File("./"));
			if (filec.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
				System.out.println("getCurrentDirectory(): "
						+ filec.getCurrentDirectory());
				System.out.println("getSelectedFile() : "
						+ filec.getSelectedFile());

				/*
				 * FileDialog fileDialog = new FileDialog(this, "Choose a file",
				 * FileDialog.SAVE); System.out.println("dopo set visible");
				 * 
				 * try { fileDialog.setVisible(true); } catch (Exception e) { //
				 * TODO Auto-generated catch block e.printStackTrace(); }
				 */

				String filename = filec.getCurrentDirectory() + "\\"
						+ filec.getSelectedFile().getName();
				// fileDialog.dispose();
				System.out
						.println("currentDir " + filec.getCurrentDirectory()
								+ " selectedfilen "
								+ filec.getSelectedFile().getName());
				FileOutputStream fos = new FileOutputStream(filename);
				ObjectOutputStream oos = new ObjectOutputStream(fos);
				oos.writeObject(object);
				oos.flush();
				fos.close();
			}
		} catch (IOException e) {
			System.out.println("Classe non salvata!!!");
			e.printStackTrace();
		}
	}
}